package com.uco.thread;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSafe01 {
    public static void main(String[] args) {
        // 创建一个账户
        BankAccount account = new BankAccount("ID-001", 1000);
        System.out.println("账户创建成功");
        Thread xm = new Thread(() -> account.fetchBalance(1000));
        Thread xh = new Thread(() -> account.fetchBalance(1000));
        xm.start();
        xh.start();
    }
}

@Data
@AllArgsConstructor
class BankAccount {
    private String id;
    private double balance;
    // 具有 final 字段修饰，AllArgsConstructor 注解会生成的构造方法会自动忽略 final 字段
    private final Lock lc = new ReentrantLock();
    // 取款流程
    // 同步方法
    public void fetchBalance(double amount) {
        // 同步代码快
        System.out.println(Thread.currentThread().getName() + " 开始取款流程");
        lc.lock();
        try {
            // 多个线程可能同时取款，导致线程安全问题
            if (balance >= amount) {
                balance -= amount;
                System.out.println(Thread.currentThread().getName() + " 取款成功，余额为：" + balance);
            } else {
                System.out.println("余额不足");
            }
        } finally {
            lc.unlock();
        }
    }
}
